<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>库存查询 - 商店进销存管理系统</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">

    <!-- 从 unpkg CDN 引入 ECharts -->
    <script src="https://unpkg.com/echarts@5.4.0/dist/echarts.min.js"></script>

    <!-- 引入 Toastify CSS 和 JS -->
    <link href="https://cdn.jsdelivr.net/npm/toastify-js/src/toastify.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/toastify-js/src/toastify.min.js"></script>

    <!-- Tailwind 配置 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        secondary: '#0FC6C2',
                        success: '#00B42A',
                        warning: '#FF7D00',
                        danger: '#F53F3F',
                        info: '#86909C'
                    },
                    fontFamily: {
                        inter: ['Inter', 'system-ui', 'sans-serif'],
                    },
                },
            }
        }
    </script>

    <!-- 自定义工具类 -->
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }

            .sidebar-item {
                @apply flex items-center px-4 py-3 text-gray-600 hover:bg-gray-50 hover:text-primary transition-all duration-200;
            }

            .sidebar-item.active {
                @apply bg-primary/10 text-primary border-l-4 border-primary;
            }

            .card-shadow {
                @apply shadow-md hover:shadow-lg transition-shadow duration-300;
            }
            .echart-container {
                width: 100%;
                height: 350px; /* 初始高度，可根据需求调整 */
            }
        }
    </style>
</head>

<body class="font-inter bg-gray-50 min-h-screen flex flex-col">
<!-- 顶部导航栏 -->
<header class="bg-white shadow-sm">
    <div class="container mx-auto px-4 py-3 flex justify-between items-center">
        <div class="flex items-center space-x-2">
            <i class="fa fa-cubes text-primary text-2xl"></i>
            <h1 class="text-xl font-bold text-gray-800">商店进销存管理系统</h1>
        </div>

        <div class="flex items-center space-x-6">
            <div class="relative">
                <input type="text" placeholder="搜索..."
                       class="pl-10 pr-4 py-2 rounded-full border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary">
                <i class="fa fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
            </div>

            <div class="flex items-center space-x-4">
                <button class="text-gray-600 hover:text-primary transition-colors">
                    <i class="fa fa-bell-o text-xl"></i>
                </button>
                <button class="text-gray-600 hover:text-primary transition-colors">
                    <i class="fa fa-cog text-xl"></i>
                </button>
                <div class="flex items-center space-x-2 cursor-pointer">
                    <img src="https://picsum.photos/200/200" alt="用户头像" class="w-8 h-8 rounded-full object-cover">
                    <span class="text-gray-700">管理员</span>
                </div>
            </div>
        </div>
    </div>
</header>

<div class="flex flex-1 overflow-hidden">
    <!-- 侧边栏导航 -->
    <aside class="w-64 bg-white shadow-md h-[calc(100vh-64px)] overflow-y-auto transition-all duration-300">
        <nav class="py-4">
            <div class="px-4 mb-4">
                <h2 class="text-xs font-semibold text-gray-400 uppercase tracking-wider">主菜单</h2>
            </div>

            <a href="index.html" class="sidebar-item" data-path="index.html">
                <i class="fa fa-tachometer w-5 h-5 mr-3"></i>
                <span>仪表盘</span>
            </a>

            <div class="px-4 mt-6 mb-2">
                <h2 class="text-xs font-semibold text-gray-400 uppercase tracking-wider">基础信息</h2>
            </div>

            <a href="productlist.html" class="sidebar-item" data-path="productlist.html">
                <i class="fa fa-shopping-bag w-5 h-5 mr-3"></i>
                <span>商品管理</span>
            </a>

            <a href="categorylist.html" class="sidebar-item" data-path="categorylist.html">
                <i class="fa fa-th-large w-5 h-5 mr-3"></i>
                <span>类别管理</span>
            </a>

            <a href="supplierlist.html" class="sidebar-item" data-path="supplierlist.html">
                <i class="fa fa-truck w-5 h-5 mr-3"></i>
                <span>供应商管理</span>
            </a>

            <div class="px-4 mt-6 mb-2">
                <h2 class="text-xs font-semibold text-gray-400 uppercase tracking-wider">库存管理</h2>
            </div>

            <a href="warehouselist.html" class="sidebar-item" data-path="warehouselist.html">
                <i class="fa fa-archive w-5 h-5 mr-3"></i>
                <span>仓库管理</span>
            </a>

            <a href="inventorylist.html" class="sidebar-item active" data-path="inventorylist.html">
                <i class="fa fa-list-alt w-5 h-5 mr-3"></i>
                <span>库存查询</span>
            </a>

            <a href="instock.html" class="sidebar-item" data-path="instock.html">
                <i class="fa fa-sign-in w-5 h-5 mr-3"></i>
                <span>入库管理</span>
            </a>

            <a href="outstock.html" class="sidebar-item " data-path="outstock.html">
                <i class="fa fa-sign-out w-5 h-5 mr-3"></i>
                <span>出库管理</span>
            </a>

            <a href="transfer.html" class="sidebar-item" data-path="transfer.html">
                <i class="fa fa-exchange w-5 h-5 mr-3"></i>
                <span>转仓管理</span>
            </a>

            <div class="px-4 mt-6 mb-2">
                <h2 class="text-xs font-semibold text-gray-400 uppercase tracking-wider">统计分析</h2>
            </div>

            <a href="../statistics/sales.html" class="sidebar-item">
                <i class="fa fa-line-chart w-5 h-5 mr-3"></i>
                <span>销售统计</span>
            </a>

            <a href="../statistics/inventory.html" class="sidebar-item">
                <i class="fa fa-pie-chart w-5 h-5 mr-3"></i>
                <span>库存分析</span>
            </a>

            <div class="px-4 mt-6 mb-2">
                <h2 class="text-xs font-semibold text-gray-400 uppercase tracking-wider">系统设置</h2>
            </div>

            <a href="salesman.html" class="sidebar-item" data-path="salesman.html">
                <i class="fa fa-user-circle w-5 h-5 mr-3"></i>
                <span>用户管理</span>
            </a>


            <a href="backup.html" class="sidebar-item" data-path="system/logs.html">
                <i class="fa fa-history w-5 h-5 mr-3"></i>
                <span>数据库备份与恢复</span>
            </a>
        </nav>
    </aside>

    <!-- 主内容区域 -->
    <main class="flex-1 overflow-y-auto bg-gray-50 p-6">
        <div class="container mx-auto">
            <!-- 页面标题 -->
            <div class="mb-6">
                <h2 class="text-[clamp(1.5rem,3vw,2rem)] font-bold text-gray-800">库存查询</h2>
                <p class="text-gray-500 mt-1">查看和管理所有商品的库存信息</p>
            </div>

            <!-- 操作按钮 -->
            <div class="mb-4 flex justify-between items-center">
                <button id="exportReportBtn" class="bg-primary text-white px-4 py-2 rounded-md hover:bg-primary/90 flex items-center">
                    <i class="fa fa-download mr-2"></i> 导出报表
                </button>
                <div class="flex space-x-2">
                    <button class="bg-gray-100 text-gray-600 px-4 py-2 rounded-md hover:bg-gray-200" id="filterBtn">
                        <i class="fa fa-filter mr-1"></i> 高级筛选
                    </button>
                    <button class="bg-gray-100 text-gray-600 px-4 py-2 rounded-md hover:bg-gray-200" id="refreshBtn">
                        <i class="fa fa-refresh mr-1"></i> 刷新
                    </button>
                </div>
            </div>

            <!-- 筛选表单 -->
            <div id="filterForm" class="mb-4 bg-white rounded-lg p-4 card-shadow hidden">
                <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">商品名称</label>
                        <input type="text" id="filterName" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent" placeholder="输入商品名称">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">商品类别</label>
                        <select id="filterCategory" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent">
                            <option value="">全部类别</option>
                            <!-- 类别选项将通过JS动态渲染 -->
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">仓库</label>
                        <select id="filterWarehouse" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent">
                            <option value="">全部仓库</option>
                            <!-- 仓库选项将通过JS动态渲染 -->
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">库存状态</label>
                        <select id="filterStatus" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent">
                            <option value="">全部状态</option>
                            <option value="normal">正常库存</option>
                            <option value="warning">库存警告</option>
                            <option value="critical">库存不足</option>
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">最低库存量</label>
                        <input type="number" id="minStock" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent" placeholder="输入最低库存量">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">最高库存量</label>
                        <input type="number" id="maxStock" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent" placeholder="输入最高库存量">
                    </div>
                    <div class="flex items-end space-x-2">
                        <button id="applyFilterBtn" class="flex-1 bg-primary text-white px-4 py-2 rounded-md hover:bg-primary/90 flex items-center justify-center">
                            <i class="fa fa-search mr-2"></i> 搜索
                        </button>
                        <button id="resetFilterBtn" class="px-4 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50">
                            重置
                        </button>
                    </div>
                </div>
            </div>

            <!-- 库存列表 -->
            <div class="bg-white rounded-xl p-6 card-shadow">
                <div class="overflow-x-auto">
                    <table class="w-full">
                        <thead>
                        <tr class="border-b border-gray-200">
                            <th class="py-3 text-left text-sm font-medium text-gray-500">商品ID</th>
                            <th class="py-3 text-left text-sm font-medium text-gray-500">商品信息</th>
                            <th class="py-3 text-left text-sm font-medium text-gray-500">类别</th>
                            <th class="py-3 text-left text-sm font-medium text-gray-500">仓库</th>
                            <th class="py-3 text-left text-sm font-medium text-gray-500">库存数量</th>
                            <th class="py-3 text-left text-sm font-medium text-gray-500">安全库存</th>
                            <th class="py-3 text-left text-sm font-medium text-gray-500">状态</th>
                            <th class="py-3 text-left text-sm font-medium text-gray-500">操作</th>
                        </tr>
                        </thead>
                        <tbody id="inventoryTable">
                        <!-- 数据将通过JS动态渲染 -->
                        <tr>
                            <td colspan="8" class="py-4 text-center">
                                <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
                                <p class="mt-2 text-gray-600">加载库存数据中...</p>
                            </td>
                        </tr>
                        </tbody>
                    </table>
                </div>

                <!-- 分页控件 -->
                <div class="mt-6 flex justify-between items-center">
                    <div class="text-sm text-gray-500" id="paginationInfo">共 0 条记录</div>
                    <div class="flex space-x-1" id="paginationControls">
                        <!-- 分页控件将通过JS动态渲染 -->
                    </div>
                </div>
            </div>

            <!-- 库存图表 -->
            <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mt-6">
                <!-- 库存总量统计 -->
                <div class="bg-white rounded-xl p-6 card-shadow">
                    <h3 class="text-lg font-semibold text-gray-800 mb-4">库存总量统计</h3>
                    <div class="bg-gray-50 p-4 rounded-lg echart-container" id="inventoryBarChart">
                        <!-- ECharts图表将通过JS动态渲染 -->
                        <div class="text-center py-8 text-gray-500">
                            <i class="fa fa-spinner fa-spin text-xl mb-2"></i>
                            <p>加载中...</p>
                        </div>
                    </div>
                </div>

                <!-- 库存状态分布 -->
                <div class="bg-white rounded-xl p-6 card-shadow">
                    <h3 class="text-lg font-semibold text-gray-800 mb-4">库存状态分布</h3>
                    <div class="bg-gray-50 p-4 rounded-lg echart-container" id="inventoryStatusChart">
                        <!-- ECharts图表将通过JS动态渲染 -->
                        <div class="text-center py-8 text-gray-500">
                            <i class="fa fa-spinner fa-spin text-xl mb-2"></i>
                            <p>加载中...</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </main>
</div>
<!-- 页脚 -->
<footer class="bg-white py-4 border-t border-gray-200">
    <div class="container mx-auto px-4 text-center text-gray-500 text-sm">
        <p>© 2025 商店进销存管理系统 - 版权所有</p>
    </div>
</footer>

<!-- 库存详情模态框 -->
<div id="inventoryDetailModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
    <div class="bg-white rounded-xl w-full max-w-2xl max-h-[90vh] overflow-y-auto">
        <div class="p-6 border-b border-gray-200 flex justify-between items-center">
            <h3 class="text-xl font-bold text-gray-800" id="detailModalTitle">库存详情</h3>
            <button id="closeDetailModal" class="text-gray-400 hover:text-gray-600">
                <i class="fa fa-times text-xl"></i>
            </button>
        </div>
        <div class="p-6" id="inventoryDetailContent">
            <!-- 库存详情内容将通过JS动态渲染 -->
            <div class="text-center py-8 text-gray-500">
                <i class="fa fa-spinner fa-spin text-xl mb-2"></i>
                <p>加载中...</p>
            </div>
        </div>
        <div class="p-6 border-t border-gray-200 flex justify-end">
            <button id="closeDetailBtn" class="px-4 py-2 bg-gray-100 text-gray-700 rounded-md hover:bg-gray-200">
                关闭
            </button>
        </div>
    </div>
</div>

<script>
    // 应用状态管理
    const appState = {
        globalData: {
            categories: {}, // 存储类别数据
            warehouses: {},  // 存储仓库数据
            allProducts: []     // 存储所有产品数据(未筛选)
        },
        inventory: {
            currentPage: 1,
            pageSize: 10,
            totalRecords: 0,
            totalPages: 1,
            filter: {
                name: '',
                categoryId: '',
                warehouseId: '',
                status: '',
                minStock: '',
                maxStock: ''
            },
            data: []
        },
        apiBaseUrl: 'http://localhost:8088' // 替换为实际API基础URL
    };

    // DOM加载完成后执行
    document.addEventListener('DOMContentLoaded', () => {
        console.log('页面初始化开始');

        // 初始化页面
        initPage();

        // 绑定事件监听器
        bindEventListeners();

        console.log('页面初始化完成');
    });

    // 初始化页面
    function initPage() {
        console.log('加载库存数据...');
        // 加载库存数据（包含类别、仓库和图表数据）
        loadInventoryData();

        // 初始化图表
        initCharts();
    }

    // 绑定事件监听器
    function bindEventListeners() {
        // 筛选按钮点击事件
        document.getElementById('filterBtn').addEventListener('click', toggleFilterForm);

        // 应用筛选按钮点击事件
        document.getElementById('applyFilterBtn').addEventListener('click', applyFilter);

        // 重置筛选按钮点击事件
        document.getElementById('resetFilterBtn').addEventListener('click', resetFilter);

        // 关闭详情模态框按钮点击事件
        document.getElementById('closeDetailModal').addEventListener('click', closeInventoryDetailModal);
        document.getElementById('closeDetailBtn').addEventListener('click', closeInventoryDetailModal);

        // 刷新按钮点击事件
        document.getElementById('refreshBtn').addEventListener('click', () => {
            console.log('用户点击刷新按钮');
            loadInventoryData();
        });

        // 导出报表按钮点击事件
        document.getElementById('exportReportBtn').addEventListener('click', exportReport);
    }

    // 导出报表
    function exportReport() {
        console.log('导出报表功能触发');
        showSuccessToast('报表导出功能开发中');
    }

    // 切换筛选表单显示/隐藏
    function toggleFilterForm() {
        const filterForm = document.getElementById('filterForm');
        filterForm.classList.toggle('hidden');
    }

    // 应用筛选
    function applyFilter() {
        console.log('应用筛选条件');
        appState.inventory.currentPage = 1;
        appState.inventory.filter.name = document.getElementById('filterName').value;
        appState.inventory.filter.categoryId = document.getElementById('filterCategory').value;
        appState.inventory.filter.warehouseId = document.getElementById('filterWarehouse').value;
        appState.inventory.filter.status = document.getElementById('filterStatus').value;
        appState.inventory.filter.minStock = document.getElementById('minStock').value;
        appState.inventory.filter.maxStock = document.getElementById('maxStock').value;

        loadInventoryData();
    }

    // 重置筛选
    function resetFilter() {
        console.log('重置筛选条件');
        document.getElementById('filterName').value = '';
        document.getElementById('filterCategory').value = '';
        document.getElementById('filterWarehouse').value = '';
        document.getElementById('filterStatus').value = '';
        document.getElementById('minStock').value = '';
        document.getElementById('maxStock').value = '';

        appState.inventory.currentPage = 1;
        appState.inventory.filter = {
            name: '',
            categoryId: '',
            warehouseId: '',
            status: '',
            minStock: '',
            maxStock: ''
        };

        loadInventoryData();
    }

    // 加载库存数据（通过API接口）
    // 加载库存数据（通过API接口）
    function loadInventoryData() {
        console.log(`加载第 ${appState.inventory.currentPage} 页库存数据，每页 ${appState.inventory.pageSize} 条记录`);

        // 显示加载状态
        const inventoryTable = document.getElementById('inventoryTable');
        inventoryTable.innerHTML = `
        <tr>
            <td colspan="8" class="py-4 text-center">
                <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
                <p class="mt-2 text-gray-600">加载库存数据中...</p>
            </td>
        </tr>
    `;

        // 构建请求参数
        const buildRequestParams = () => {
            const params = new URLSearchParams();

            // 1. 分页参数（确保与后端一致）
            params.append('page', (appState.inventory.currentPage - 1).toString()); // 前端页码从1开始，后端从0开始
            params.append('size', appState.inventory.pageSize.toString());

            // 2. 文本筛选参数（处理空字符串和undefined）
            if (appState.inventory.filter.name?.trim() !== '') {
                params.append('name', appState.inventory.filter.name.trim());
            }

            // 3. 数值筛选参数（处理0和有效ID）
            if (appState.inventory.filter.categoryId !== undefined && appState.inventory.filter.categoryId !== null) {
                params.append('categoryId', appState.inventory.filter.categoryId.toString());
            }

            if (appState.inventory.filter.warehouseId !== undefined && appState.inventory.filter.warehouseId !== null) {
                params.append('warehouseId', appState.inventory.filter.warehouseId.toString());
            }

            // 4. 库存状态参数（处理有效值）
            const validStatuses = ['normal', 'warning', 'critical'];
            if (appState.inventory.filter.status && validStatuses.includes(appState.inventory.filter.status)) {
                params.append('status', appState.inventory.filter.status);
            }

            // 5. 库存范围参数（处理数值有效性）
            if (appState.inventory.filter.minStock !== undefined && !isNaN(Number(appState.inventory.filter.minStock))) {
                params.append('minStock', appState.inventory.filter.minStock.toString());
            }

            if (appState.inventory.filter.maxStock !== undefined && !isNaN(Number(appState.inventory.filter.maxStock))) {
                params.append('maxStock', appState.inventory.filter.maxStock.toString());
            }

            return params;
        };

        // 使用示例
        const params = buildRequestParams();
        console.log('API请求参数:', params.toString());

        // 调用API接口
        fetch(`${appState.apiBaseUrl}/warehouseProduct?${params}`)
            .then(response => {
                console.log('API响应状态:', response.status);
                if (!response.ok) {
                    throw new Error(`HTTP错误! 状态码: ${response.status}`);
                }
                return response.json();
            })
            .then(response => {
                console.log('API响应数据:', response);

                // 处理响应数据
                processInventoryResponse(response);

                // 更新总页数和总记录数
                appState.inventory.totalPages = response.data.totalPages || 1;
                appState.inventory.totalRecords = response.data.totalElements || 0;

                // 刷新分页控件
                updatePagination();

                console.log(`成功加载 ${appState.inventory.data.length} 条库存数据`);
            })
            .catch(error => {
                console.error('加载库存数据失败:', error);
                showErrorToast('加载库存数据失败，请检查网络连接或稍后重试');
                const inventoryTable = document.getElementById('inventoryTable');
                inventoryTable.innerHTML = `
                <tr>
                    <td colspan="8" class="py-4 text-center text-red-500">
                        <i class="fa fa-exclamation-circle mr-2"></i> ${error.message}
                    </td>
                </tr>
            `;
            });
    }

    /**
     * 处理库存响应数据
     */
// 修改数据处理函数，保存原始数据
    function processInventoryResponse(response) {
        // 检查响应状态
        if (!response || !response.data || !response.data.content) {
            console.error('API响应格式不正确:', response);
            showErrorToast('获取库存数据失败，响应格式不正确');
            return;
        }

        const allProducts = response.data.content;

        // 提取并存储完整类别数据(不依赖当前页)
        const categoriesMap = {};
        allProducts.forEach(product => {
            if (product.categoryId && product.categoryName) {
                categoriesMap[product.categoryId] = product.categoryName;
            }
        });
        appState.globalData.categories = categoriesMap;

        // 提取并存储完整仓库数据(不依赖当前页)
        const warehousesMap = {};
        allProducts.forEach(product => {
            if (product.warehouseName) {
                const warehouseId = product.warehouseName; // 使用仓库名称作为ID
                warehousesMap[warehouseId] = product.warehouseName;
            }
        });
        appState.globalData.warehouses = warehousesMap;

        // 保存完整产品数据
        appState.globalData.allProducts = allProducts;

        // 应用筛选条件
        applyFilterToData();

        // 填充筛选器下拉框(使用完整数据)
        populateFilterDropdowns();

        // 更新应用状态
        appState.inventory.totalRecords = response.data.totalElements || 0;
        appState.inventory.totalPages = response.data.totalPages || 1;
        appState.inventory.currentPage = response.data.number + 1 || 1;

        // 渲染库存表格
        renderInventoryTable();

        // 更新分页信息
        updatePagination();

        // 更新图表数据
        updateCharts(appState.inventory.data);
    }

    // 创建新的筛选函数，仅处理表格数据
    function applyFilterToData() {
        const { name, categoryId, warehouseId, status, minStock, maxStock } = appState.inventory.filter;
        let filteredData = [...appState.globalData.allProducts];

        // 应用筛选条件
        if (name) {
            const searchTerm = name.toLowerCase();
            filteredData = filteredData.filter(product =>
                product.productName?.toLowerCase().includes(searchTerm)
            );
        }

        if (categoryId) {
            filteredData = filteredData.filter(product =>
                product.categoryId === categoryId
            );
        }

        if (warehouseId) {
            filteredData = filteredData.filter(product =>
                product.warehouseName === warehouseId
            );
        }

        if (status) {
            let stockThreshold;
            if (status === 'critical') stockThreshold = 1;
            else if (status === 'warning') stockThreshold = 5;

            filteredData = filteredData.filter(product => {
                if (status === 'normal') {
                    return product.productStock > 5;
                } else {
                    return product.productStock <= stockThreshold;
                }
            });
        }

        if (minStock && !isNaN(Number(minStock))) {
            filteredData = filteredData.filter(product =>
                product.productStock >= Number(minStock)
            );
        }

        if (maxStock && !isNaN(Number(maxStock))) {
            filteredData = filteredData.filter(product =>
                product.productStock <= Number(maxStock)
            );
        }

        // 更新当前显示的数据
        appState.inventory.data = filteredData;
    }

    // 修改应用筛选函数，不再重新加载数据，而是直接筛选
    function applyFilter() {
        console.log('应用筛选条件');

        // 保存筛选条件
        appState.inventory.currentPage = 1;
        appState.inventory.filter.name = document.getElementById('filterName').value;
        appState.inventory.filter.categoryId = document.getElementById('filterCategory').value;
        appState.inventory.filter.warehouseId = document.getElementById('filterWarehouse').value;
        appState.inventory.filter.status = document.getElementById('filterStatus').value;
        appState.inventory.filter.minStock = document.getElementById('minStock').value;
        appState.inventory.filter.maxStock = document.getElementById('maxStock').value;

        // 应用筛选到现有数据
        applyFilterToData();

        // 重新渲染表格
        renderInventoryTable();

        // 更新分页
        updatePagination();

        // 更新图表
        updateCharts(appState.inventory.data);
    }

    // 修改重置筛选函数，不再重新加载数据
    function resetFilter() {
        console.log('重置筛选条件');

        // 清空筛选表单
        document.getElementById('filterName').value = '';
        document.getElementById('filterCategory').value = '';
        document.getElementById('filterWarehouse').value = '';
        document.getElementById('filterStatus').value = '';
        document.getElementById('minStock').value = '';
        document.getElementById('maxStock').value = '';

        // 重置筛选状态
        appState.inventory.currentPage = 1;
        appState.inventory.filter = {
            name: '',
            categoryId: '',
            warehouseId: '',
            status: '',
            minStock: '',
            maxStock: ''
        };

        // 恢复显示所有数据
        appState.inventory.data = [...appState.globalData.allProducts];

        // 重新渲染表格
        renderInventoryTable();

        // 更新分页
        updatePagination();

        // 更新图表
        updateCharts(appState.globalData.allProducts);
    }

    // 填充筛选器下拉框
    function populateFilterDropdowns() {
        // 填充类别下拉框
        const categorySelect = document.getElementById('filterCategory');
        categorySelect.innerHTML = '<option value="">全部类别</option>';

        Object.entries(appState.globalData.categories).forEach(([id, name]) => {
            const option = document.createElement('option');
            option.value = id;
            option.textContent = name;
            categorySelect.appendChild(option);
        });

        // 填充仓库下拉框
        const warehouseSelect = document.getElementById('filterWarehouse');
        warehouseSelect.innerHTML = '<option value="">全部仓库</option>';

        Object.entries(appState.globalData.warehouses).forEach(([id, name]) => {
            const option = document.createElement('option');
            option.value = id;
            option.textContent = name;
            warehouseSelect.appendChild(option);
        });
    }

    // 渲染库存表格
    function renderInventoryTable() {
        const inventoryTable = document.getElementById('inventoryTable');

        if (appState.inventory.data.length === 0) {
            inventoryTable.innerHTML = `
            <tr>
                <td colspan="8" class="py-4 text-center text-gray-500">
                    <i class="fa fa-search-minus text-2xl mb-2"></i>
                    <p>没有找到匹配的库存记录</p>
                </td>
            </tr>
        `;
            return;
        }

        let html = '';

        appState.inventory.data.forEach(item => {
            let statusClass = 'bg-green-100 text-green-800';
            let statusText = '正常';

            if (item.status === 'warning') {
                statusClass = 'bg-yellow-100 text-yellow-800';
                statusText = '警告';
            } else if (item.status === 'critical') {
                statusClass = 'bg-red-100 text-red-800';
                statusText = '不足';
            }

            html += `
            <tr class="border-b border-gray-100 hover:bg-gray-50 transition-colors">
                <td class="py-3 text-sm text-gray-700">${item.productId || 'N/A'}</td>
                <td class="py-3">
                    <div class="flex items-center">
                        <img src="${item.productImage || 'https://picsum.photos/200/200'}" alt="${item.productName || '未知商品'}" class="w-10 h-10 rounded-md object-cover mr-3">
                        <div>
                            <p class="text-sm font-medium text-gray-900">${item.productName || '未知商品'}</p>
                            <p class="text-xs text-gray-500">ID: ${item.productId || 'N/A'}</p>
                        </div>
                    </div>
                </td>
                <td class="py-3 text-sm text-gray-700">${item.categoryName || '未知类别'}</td>
                <td class="py-3 text-sm text-gray-700">${item.warehouseName || '未知仓库'}</td>
                <td class="py-3 text-sm font-medium ${item.productStock < (item.stockWarningLevel || 5) ? 'text-red-600' : 'text-gray-900'}">
                    ${item.productStock || 0} ${item.unit || ''}
                </td>
                <td class="py-3 text-sm text-gray-700">${item.stockWarningLevel || 0}</td>
                <td class="py-3">
                    <span class="px-2 py-1 text-xs rounded-full ${statusClass}">${statusText}</span>
                </td>
                <td class="py-3">
                    <span class="px-2 py-1 text-xs rounded-full ${item.productStatus === 'active' ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-800'}">
                        ${item.productStatus === 'active' ? '已激活' : '未激活'}
                    </span>
                </td>
                <td class="py-3">
                    <button class="text-primary hover:text-primary/80 mr-3" onclick="showInventoryDetail(${item.productId})">
                        <i class="fa fa-eye"></i> 查看
                    </button>
                </td>
            </tr>
        `;
        });

        inventoryTable.innerHTML = html;
    }

    // 更新分页控件
    function updatePagination() {
        const { currentPage, totalPages, totalRecords, pageSize } = appState.inventory;

        // 更新分页信息文本
        document.getElementById('paginationInfo').textContent = `共 ${totalRecords} 条记录，当前第 ${currentPage}/${totalPages} 页`;

        // 更新分页控件
        const paginationControls = document.getElementById('paginationControls');
        paginationControls.innerHTML = '';

        // 添加上一页按钮
        if (currentPage > 1) {
            const prevButton = document.createElement('button');
            prevButton.className = 'px-3 py-1 rounded border border-gray-300 text-gray-700 hover:bg-gray-50';
            prevButton.innerHTML = '<i class="fa fa-chevron-left"></i>';
            prevButton.addEventListener('click', () => {
                appState.inventory.currentPage--;
                loadInventoryData();
            });
            paginationControls.appendChild(prevButton);
        } else {
            // 第一页时添加禁用状态
            const disabledPrevButton = document.createElement('button');
            disabledPrevButton.className = 'px-3 py-1 rounded border border-gray-300 text-gray-400 cursor-not-allowed';
            disabledPrevButton.innerHTML = '<i class="fa fa-chevron-left"></i>';
            paginationControls.appendChild(disabledPrevButton);
        }

        // 添加页码按钮
        const startPage = Math.max(1, currentPage - 2);
        const endPage = Math.min(totalPages, startPage + 4);

        // 添加首页按钮（若不在第一页）
        if (startPage > 1) {
            addPageButton(1);
            if (startPage > 2) {
                addEllipsis();
            }
        }

        // 添加中间页码
        for (let i = startPage; i <= endPage; i++) {
            addPageButton(i);
        }

        // 添加尾页按钮（若不在最后一页）
        if (endPage < totalPages) {
            if (endPage < totalPages - 1) {
                addEllipsis();
            }
            addPageButton(totalPages);
        }

        // 添加下一页按钮
        if (currentPage < totalPages) {
            const nextButton = document.createElement('button');
            nextButton.className = 'px-3 py-1 rounded border border-gray-300 text-gray-700 hover:bg-gray-50';
            nextButton.innerHTML = '<i class="fa fa-chevron-right"></i>';
            nextButton.addEventListener('click', () => {
                appState.inventory.currentPage++;
                loadInventoryData();
            });
            paginationControls.appendChild(nextButton);
        } else {
            // 最后一页时添加禁用状态
            const disabledNextButton = document.createElement('button');
            disabledNextButton.className = 'px-3 py-1 rounded border border-gray-300 text-gray-400 cursor-not-allowed';
            disabledNextButton.innerHTML = '<i class="fa fa-chevron-right"></i>';
            paginationControls.appendChild(disabledNextButton);
        }

        // 添加页面大小选择器
        const pageSizeSelector = createPageSizeSelector();
        paginationControls.appendChild(pageSizeSelector);

        // 辅助函数：添加页码按钮
        function addPageButton(pageNum) {
            const pageButton = document.createElement('button');
            pageButton.className = `px-3 py-1 mx-1 rounded border border-gray-300 ${pageNum === currentPage ? 'bg-primary text-white' : 'text-gray-700 hover:bg-gray-50'}`;
            pageButton.textContent = pageNum;
            pageButton.addEventListener('click', () => {
                appState.inventory.currentPage = pageNum;
                loadInventoryData();
            });
            paginationControls.appendChild(pageButton);
        }

        // 辅助函数：添加省略号
        function addEllipsis() {
            const ellipsis = document.createElement('span');
            ellipsis.className = 'px-2 text-gray-500';
            ellipsis.textContent = '...';
            paginationControls.appendChild(ellipsis);
        }

        // 创建页面大小选择器
        function createPageSizeSelector() {
            const selectorContainer = document.createElement('div');
            selectorContainer.className = 'ml-4 flex items-center';

            const label = document.createElement('label');
            label.className = 'text-gray-700 mr-2 text-sm';
            label.textContent = '每页显示：';
            selectorContainer.appendChild(label);

            const selector = document.createElement('select');
            selector.className = 'px-2 py-1 border border-gray-300 rounded text-gray-700 text-sm';
            [10, 20, 50, 100].forEach(size => {
                const option = document.createElement('option');
                option.value = size;
                option.textContent = `${size}条`;
                option.selected = size === pageSize;
                selector.appendChild(option);
            });

            selector.addEventListener('change', () => {
                appState.inventory.pageSize = parseInt(selector.value);
                appState.inventory.currentPage = 1; // 切换页大小后重置为第一页
                loadInventoryData();
            });

            selectorContainer.appendChild(selector);
            return selectorContainer;
        }
    }

    // 显示库存详情
    function showInventoryDetail(productId) {
        const inventoryItem = appState.inventory.data.find(item => item.productId === productId);

        if (!inventoryItem) {
            showErrorToast('找不到该商品的库存信息');
            return;
        }

        let statusClass = 'bg-green-100 text-green-800';
        let statusText = '正常';

        if (inventoryItem.status === 'warning') {
            statusClass = 'bg-yellow-100 text-yellow-800';
            statusText = '警告';
        } else if (inventoryItem.status === 'critical') {
            statusClass = 'bg-red-100 text-red-800';
            statusText = '不足';
        }

        // 更新模态框内容
        document.getElementById('detailModalTitle').textContent = `库存详情: ${inventoryItem.productName || '未知商品'}`;
        document.getElementById('inventoryDetailContent').innerHTML = `
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
                <div class="bg-gray-50 rounded-lg p-4 mb-4">
                    <img src="${inventoryItem.productImage || 'https://picsum.photos/200/200'}" alt="${inventoryItem.productName || '未知商品'}" class="w-full h-48 object-cover rounded-lg">
                </div>
                <div class="grid grid-cols-2 gap-4">
                    <div class="bg-gray-50 rounded-lg p-4">
                        <p class="text-sm text-gray-500 mb-1">商品ID</p>
                        <p class="text-lg font-semibold text-gray-900">${inventoryItem.productId || 'N/A'}</p>
                    </div>
                    <div class="bg-gray-50 rounded-lg p-4">
                        <p class="text-sm text-gray-500 mb-1">商品名称</p>
                        <p class="text-lg font-semibold text-gray-900">${inventoryItem.productName || '未知商品'}</p>
                    </div>
                    <div class="bg-gray-50 rounded-lg p-4">
                        <p class="text-sm text-gray-500 mb-1">商品类别</p>
                        <p class="text-lg font-semibold text-gray-900">${inventoryItem.categoryName || '未知类别'}</p>
                    </div>
                    <div class="bg-gray-50 rounded-lg p-4">
                        <p class="text-sm text-gray-500 mb-1">存放仓库</p>
                        <p class="text-lg font-semibold text-gray-900">${inventoryItem.warehouseName || '未知仓库'}</p>
                    </div>
                </div>
            </div>
            <div>
                <div class="bg-gray-50 rounded-lg p-4 mb-4">
                    <div class="flex justify-between items-center mb-4">
                        <h4 class="font-semibold text-gray-800">库存状态</h4>
                        <span class="px-2 py-1 text-xs rounded-full ${statusClass}">${statusText}</span>
                    </div>
                    <div class="flex justify-between items-center mb-2">
                        <p class="text-gray-600">当前库存:</p>
                        <p class="text-xl font-bold ${inventoryItem.productStock < (inventoryItem.stockWarningLevel || 5) ? 'text-red-600' : 'text-gray-900'}">${inventoryItem.productStock || 0} ${inventoryItem.unit || ''}</p>
                    </div>
                    <div class="flex justify-between items-center mb-2">
                        <p class="text-gray-600">安全库存:</p>
                        <p class="text-lg font-medium text-gray-900">${inventoryItem.stockWarningLevel || 0} ${inventoryItem.unit || ''}</p>
                    </div>
                    <div class="w-full bg-gray-200 rounded-full h-2.5 mt-4">
                        <div class="bg-primary h-2.5 rounded-full" style="width: ${Math.min(100, (inventoryItem.productStock || 0) / (inventoryItem.stockWarningLevel || 1) * 100)}%"></div>
                    </div>
                    <p class="text-xs text-gray-500 mt-2">库存水平: ${Math.min(100, Math.round((inventoryItem.productStock || 0) / (inventoryItem.stockWarningLevel || 1) * 100))}%</p>
                </div>

                <div class="bg-gray-50 rounded-lg p-4 mb-4">
                    <h4 class="font-semibold text-gray-800 mb-3">商品规格</h4>
                    <p class="text-gray-700">${inventoryItem.specification || '无'}</p>
                </div>

                <div class="bg-gray-50 rounded-lg p-4 mb-4">
                    <h4 class="font-semibold text-gray-800 mb-3">供应商信息</h4>
                    <div class="flex items-center">
                        <i class="fa fa-truck text-primary mr-2"></i>
                        <p class="text-gray-700">${inventoryItem.supplierName || '无'}</p>
                    </div>
                </div>

                <div class="bg-gray-50 rounded-lg p-4 mb-4">
                    <h4 class="font-semibold text-gray-800 mb-3">最后更新</h4>
                    <p class="text-gray-700">${inventoryItem.lastUpdateTime || '未知'}</p>
                </div>

                <div class="bg-gray-50 rounded-lg p-4">
                    <h4 class="font-semibold text-gray-800 mb-3">商品描述</h4>
                    <p class="text-gray-700">${inventoryItem.description || '无描述'}</p>
                </div>
            </div>
        </div>
    `;

        // 显示模态框
        document.getElementById('inventoryDetailModal').classList.remove('hidden');
    }

    // 关闭库存详情模态框
    function closeInventoryDetailModal() {
        document.getElementById('inventoryDetailModal').classList.add('hidden');
    }

    // 初始化图表
    function initCharts() {
        console.log('初始化图表...');

        // 库存总量统计图表
        const barChartContainer = document.getElementById('inventoryBarChart');
        if (!barChartContainer) {
            console.error('找不到库存总量统计图表容器');
            return;
        }

        window.inventoryBarChart = echarts.init(barChartContainer);

        // 库存状态分布图表
        const statusChartContainer = document.getElementById('inventoryStatusChart');
        if (!statusChartContainer) {
            console.error('找不到库存状态分布图表容器');
            return;
        }

        window.inventoryStatusChart = echarts.init(statusChartContainer);

        // 设置图表默认配置
        const commonOption = {
            textStyle: {
                fontFamily: 'Inter, system-ui, sans-serif',
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'cross',
                    crossStyle: {
                        color: '#999'
                    }
                }
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            }
        };

        window.inventoryBarChart.setOption(commonOption);
        window.inventoryStatusChart.setOption(commonOption);

        // 监听窗口大小变化，调整图表尺寸
        window.addEventListener('resize', () => {
            if (window.inventoryBarChart) window.inventoryBarChart.resize();
            if (window.inventoryStatusChart) window.inventoryStatusChart.resize();
        });

        console.log('图表初始化完成');
    }

    /**
     * 更新图表数据
     */
    function updateCharts(products) {
        console.log(`更新图表数据，共有 ${products.length} 条商品数据`);

        if (!products || products.length === 0) {
            console.log('没有商品数据，无法更新图表');
            return;
        }

        // 确保图表已初始化
        if (!window.inventoryBarChart || !window.inventoryStatusChart) {
            initCharts();
        }

        // 计算按类别分组的库存统计
        const categoryMap = {};
        products.forEach(product => {
            const categoryId = product.categoryId || '未知类别';
            const categoryName = product.categoryName || `类别${categoryId}`;
            const stock = product.productStock || 0;

            if (!categoryMap[categoryId]) {
                categoryMap[categoryId] = {
                    id: categoryId,
                    name: categoryName,
                    value: 0
                };
            }

            categoryMap[categoryId].value += stock;
        });

        // 转换为图表所需格式
        const stockByCategory = Object.values(categoryMap);

        // 计算库存状态分布
        const statusCounts = {
            normal: 0,    // 正常
            warning: 0,   // 警告
            critical: 0   // 紧急
        };

        products.forEach(product => {
            const stock = product.productStock || 0;

            if (stock <= 1) {
                statusCounts.critical++;
            } else if (stock <= 5) {
                statusCounts.warning++;
            } else {
                statusCounts.normal++;
            }
        });

        // 转换为图表所需格式
        const stockStatus = [
            { value: statusCounts.normal, name: '正常库存' },
            { value: statusCounts.warning, name: '警告库存' },
            { value: statusCounts.critical, name: '紧急库存' }
        ];

        // 库存总量统计图表数据
        const barChartOption = {
            xAxis: {
                type: 'category',
                data: stockByCategory.map(item => item.name),
                axisLabel: {
                    interval: 0,
                    rotate: 45
                }
            },
            yAxis: {
                type: 'value',
                name: '库存数量'
            },
            series: [{
                data: stockByCategory.map(item => item.value),
                type: 'bar',
                itemStyle: {
                    color: '#165DFF'
                }
            }]
        };

        // 更新柱状图
        if (window.inventoryBarChart) {
            console.log('更新库存总量统计柱状图');
            window.inventoryBarChart.setOption(barChartOption);
        }

        // 库存状态分布图表数据
        const statusChartOption = {
            tooltip: {
                trigger: 'item',
                formatter: "{a} <br/>{b} : {c} ({d}%)"
            },
            series: [{
                name: '库存状态',
                type: 'pie',
                radius: '50%',
                data: stockStatus,
                itemStyle: {
                    borderRadius: 4,
                    borderColor: '#fff',
                    borderWidth: 2
                },
                color: [
                    '#00B42A',  // 正常 - 绿色
                    '#FF7D00',  // 警告 - 橙色
                    '#F53F3F'   // 不足 - 红色
                ]
            }]
        };

        // 更新饼图
        if (window.inventoryStatusChart) {
            console.log('更新库存状态分布饼图');
            window.inventoryStatusChart.setOption(statusChartOption);
        }
    }

    // 显示错误提示
    function showErrorToast(message) {
        Toastify({
            text: message,
            duration: 3000,
            gravity: "top",
            position: "center",
            backgroundColor: "#F53F3F",
        }).showToast();
    }

    // 显示成功提示
    function showSuccessToast(message) {
        Toastify({
            text: message,
            duration: 3000,
            gravity: "top",
            position: "center",
            backgroundColor: "#00B42A",
        }).showToast();
    }
</script>
</body>
</html>